package com.task;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pojo.MovieList;
import com.service.DyService;
import com.util.HardUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.management.Query;
import java.io.File;
import java.util.*;

@Service
public class TimeTaskRemoveDyService {

    @Autowired
    private DyService dyService;


    @Value("${server.url}")
    private String server;


    @Value("${dy.home}")
    private String home;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 所有下架的电影删除
     */

    @Scheduled(cron = "0 0 10 * * MON")
    public synchronized void removeDy() {

            //如果上架的电影<1000
            QueryWrapper q2 = new QueryWrapper();
            q2.eq("is_it_on_the_shelf",1);
            int count = dyService.count(q2);
            if (count<500){
                return;
            }


            QueryWrapper q = new QueryWrapper();
            q.eq("is_it_on_the_shelf",0);
            List<MovieList> localList = dyService.list(q);


            //删除下架电影
            if (localList != null) {
                for (MovieList m : localList) {
                    String md5 = m.getMd5();
                    File file = new File(home + "dy/" + md5);
                    if (file.exists()) {
                        file.delete();
                    } else {
                        System.out.println(file.getAbsolutePath() + "文件不存在");
                    }
                    dyService.removeById(m.getId());
                }
            }
    }


    private List<MovieList> removeAll(List<MovieList> src, List<MovieList> target) {
        LinkedList<MovieList> result = new LinkedList<MovieList>(src); //大集合用linkedlist
        HashSet<MovieList> targetHash = new HashSet<MovieList>(target); //小集合用hashset
        Iterator<MovieList> iter = result.iterator(); //采用Iterator迭代器进行数据的操作

        while (iter.hasNext()) {
            MovieList m = iter.next();
            if (targetHash.contains(m)) {
                iter.remove();
            }
        }
        return result;
    }
}
